from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from backend.app import db
def get_models():
    from backend.models.lottery_result import LotteryResult
    from backend.models.ai_prediction import AIPrediction
    return LotteryResult, AIPrediction
from backend.services.ai_service import AIService
from datetime import datetime

ai_bp = Blueprint('ai', __name__)
ai_service = AIService()

@ai_bp.route('/analyze', methods=['POST'])
@jwt_required()
def analyze_lottery_data():
    """AI分析双色球数据"""
    try:
        data = request.get_json()
        start_draw = data.get('start_draw')
        end_draw = data.get('end_draw')
        custom_prompt = data.get('prompt', '')  # 获取自定义提示词
        
        # 添加调试日志
        print(f"[DEBUG] 接收到的数据: {data}")
        print(f"[DEBUG] custom_prompt: '{custom_prompt}'")
        
        if not start_draw or not end_draw:
            return jsonify({'error': '开始期数和结束期数不能为空'}), 400
        
        LotteryResult, AIPrediction = get_models()
        # 验证期数范围
        start_result = LotteryResult.query.filter_by(draw_number=start_draw).first()
        end_result = LotteryResult.query.filter_by(draw_number=end_draw).first()
        
        if not start_result or not end_result:
            return jsonify({'error': '期数不存在'}), 400
        
        # 获取期数范围内的数据
        lottery_data = LotteryResult.query.filter(
            LotteryResult.draw_date >= start_result.draw_date,
            LotteryResult.draw_date <= end_result.draw_date
        ).order_by(LotteryResult.draw_date.asc()).all()
        
        if not lottery_data:
            return jsonify({'error': '指定范围内没有数据'}), 400
        
        # 调用AI服务进行分析
        analysis_result = ai_service.analyze_lottery_data(lottery_data, custom_prompt)
        
        # 保存预测记录
        prediction = AIPrediction(
            start_draw=start_draw,
            end_draw=end_draw,
            data_count=len(lottery_data),
            analysis_result=analysis_result.get('analysis', '')
        )
        prediction.set_predicted_numbers(analysis_result.get('predictions', []))
        
        db.session.add(prediction)
        db.session.commit()
        
        return jsonify({
            'message': '分析完成',
            'data_count': len(lottery_data),
            'predictions': analysis_result.get('predictions', []),
            'analysis': analysis_result.get('analysis', ''),
            'prediction_id': prediction.id
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'分析失败: {str(e)}'}), 500

@ai_bp.route('/verify', methods=['POST'])
@jwt_required()
def verify_prediction():
    """验证预测结果"""
    try:
        data = request.get_json()
        prediction_id = data.get('prediction_id')
        
        if not prediction_id:
            return jsonify({'error': '预测ID不能为空'}), 400
        
        LotteryResult, AIPrediction = get_models()
        prediction = AIPrediction.query.get(prediction_id)
        if not prediction:
            return jsonify({'error': '预测记录不存在'}), 404
        
        # 获取下一期开奖结果
        next_draw = LotteryResult.query.filter(
            LotteryResult.draw_date > datetime.strptime(prediction.end_draw[:4] + prediction.end_draw[4:6] + prediction.end_draw[6:], '%Y%m%d').date()
        ).order_by(LotteryResult.draw_date.asc()).first()
        
        if not next_draw:
            return jsonify({'error': '下一期开奖结果尚未公布'}), 400
        
        # 验证预测结果
        verification_result = ai_service.verify_prediction(
            prediction.get_predicted_numbers(),
            next_draw
        )
        
        # 更新预测记录
        prediction.set_actual_result(next_draw.to_dict())
        prediction.win_info = verification_result.get('win_info', '')
        prediction.win_amount = verification_result.get('win_amount', 0)
        
        db.session.commit()
        
        return jsonify({
            'message': '验证完成',
            'actual_result': next_draw.to_dict(),
            'verification': verification_result,
            'prediction': prediction.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'验证失败: {str(e)}'}), 500

@ai_bp.route('/predictions', methods=['GET'])
@jwt_required()
def get_predictions():
    """获取预测记录列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        
        LotteryResult, AIPrediction = get_models()
        query = AIPrediction.query.order_by(AIPrediction.created_at.desc())
        pagination = query.paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
        
        results = [item.to_dict() for item in pagination.items]
        
        return jsonify({
            'data': results,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取预测记录失败: {str(e)}'}), 500 